package org.itboys.weixin.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.spring.interceptor.ServletContextInterceptor;
import org.itboys.mobile.dto.member.SundayWeixinMemberDto;
import org.itboys.weixin.util.ParamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信自动绑定用户和微信ID的拦截器
 * @author ChenJunhui
 *
 */
public class WeixinAutoBindLoginInterceptor extends ServletContextInterceptor {
	protected Logger logger = LoggerFactory.getLogger(getClass());


	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		super.preHandle(request, response, handler);


		//请求的URL
		String url=request.getRequestURI();
		String requestParam = ParamUtil.getRequestParam(request);
		logger.info("-------微信-执行拦截器0-----当前请求地址"+url+"，请求参数："+requestParam);


		//获取session里的微信用户
		Object object =request.getSession().getAttribute("member");
		SundayWeixinMemberDto member=
				object!=null?(SundayWeixinMemberDto)object:null;



		//补全member参数后，如果member==null，通过微信转发一下
		if((member==null)
				&&url.startsWith("/coo/weixin/")
				&&url.startsWith("/sunday/weixin/")
				&&!url.startsWith("/sunday/weixin/safe/oAuth")
				&&!url.startsWith("/sunday/weixin/session/")
				&&!url.startsWith("/coo/weixin/pay/callback/")
				){

			logger.info("--------微信-拦截器-用户为空-开始执行");

			url+="?"+requestParam;
			//把当前的地址也作为参数，发到oAuth接口下
			if(StringUtils.isNotEmpty(requestParam)){
				requestParam+="&oldUrl="+url;

			}else{
				requestParam+="?oldUrl+="+url;
			}
			String oAuthUrl="/sunday/weixin/safe/oAuth?type=999&"+requestParam;

			logger.info("--------微信-拦截器-用户为空-开始执行-转跳授权地址"+oAuthUrl);
			response.sendRedirect(oAuthUrl);
			return false;
		}



		return super.preHandle(request, response, handler);
	}
}
